
#include <QCoreApplication>
#include <QApplication>
#include <QFile>
#include <QtConcurrent>
#include <QProcess>
#include "downclient.h"

DownClient::Status DownClient::down_done_script()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QString filepath = this->currentDownDir + "/" +
            this->settings->value(USER_SCRIPT_NAME).toString();
    QFile script_file(filepath);
    if(this->settings->value(USER_RUN_SCRIPT).toBool() == false) {
        qDebug() <<  "run script is" << false;
        return NO_ERROR;
    }
    if(!script_file.exists()) {
        qDebug() << "script file not exists." << filepath;
        return NO_ERROR;
    }
    QFuture<void> future = QtConcurrent::run(this, &DownClient::processRun);
    while(!future.isFinished()) {
        QApplication::processEvents(QEventLoop::AllEvents, 100);
    }
    return NO_ERROR;
}

void DownClient::processRun()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QString cmd(this->currentDownDir + "/" +
                this->settings->value(USER_SCRIPT_NAME).toString());
    qDebug() << "cmd : " << cmd;
    QStringList param;
    param << "cmd.exe" << "/c" << cmd;
    qDebug() << param;

    QProcess process;
    process.setWorkingDirectory(this->currentDownDir);
    process.start("cmd.exe");
    process.waitForFinished(-1);

    QString errorStr = process.readAllStandardError();
    QString output = process.readAllStandardOutput();
    qDebug() << "processRun Done.";
    qDebug() << "errorStr:";
    qDebug() << errorStr;
    qDebug() << "output:";
    qDebug() << output;

    LOG("Download Done Script Run Done.");
    LOG("errorStr:\n%s", errorStr.toLatin1().data());
    LOG("output:\n%s", output.toLatin1().data());

    qDebug() << "processRun end of function";
}
